package com.hand.wfive.activity.sign

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.pdf.PdfRenderer
import android.os.Bundle
import android.os.ParcelFileDescriptor
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.efs.sdk.base.core.util.Log
import com.hand.wfive.App
import com.hand.wfive.R
import com.hand.wfive.adapter.FragmentAdapter
import com.hand.wfive.base.BaseFragment
import com.hand.wfive.base.Constant
import com.hand.wfive.entity.FileEvent
import com.hand.wfive.entity.FileModel
import com.hand.wfive.entity.Params
import com.hand.wfive.fragment.sign.SignItemFragment
import com.hand.wfive.fragment.sign.SignPreviewItemFragment
import com.hand.wfive.util.FileUtils
import com.hand.wfive.util.ImageUtils
import com.hand.wfive.util.click.singleClick
import com.hand.wfive.util.oss.OssCallBack
import com.hand.wfive.util.oss.OssRequest
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_sign_preview.qvp_sign_preview
import kotlinx.android.synthetic.main.activity_sign_preview.topBar
import org.greenrobot.eventbus.EventBus
import java.io.File

@Route(path = Constant.Path.PreviewActivity)
class PreviewActivity : BaseSignActivity() {
    val fragments = ArrayList<BaseFragment>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ARouter.getInstance().inject(this)
    }

    private fun pdfSign() {
        val suffix = mFileModel.fileId.substring(mFileModel.fileId.lastIndexOf("."))
        mFileModel.filePath = if (mFileModel.fileName.endsWith(suffix, true)) {
            "${App.getContext().cacheSignPath}/${mFileModel.fileName}"
        } else {
            "${App.getContext().cacheSignPath}/${mFileModel.fileName}${suffix}"
        }
        val file = File(mFileModel.filePath)
        if (file.exists() && FileUtils.getFileSize(file) == mFileModel.size) {
//            SignActivity.show(mContext, model)
            showPdf()
        } else {
            showLoadingTipC()
            OssRequest.getInstance().dowloadFile(
                mFileModel.fileId, mFileModel.filePath, object : OssCallBack {
                    override fun onSuccess() {
                        dismissTip()
                        showPdf()
                    }

                    override fun onFailure(msg: String) {
                        showNormalTip(if (msg.contains("下载")) "打开失败" else msg)
                    }
                })
        }
    }

    @SuppressLint("CheckResult")
    fun showPdf() {
        showLoadingTipC()
        Observable.create<ArrayList<String>> {
            val imgList = ArrayList<String>()
            val parcelFileDescriptor = ParcelFileDescriptor.open(
                File(mFileModel.filePath), ParcelFileDescriptor.MODE_READ_ONLY
            )
            if (parcelFileDescriptor != null) {
                val pdfRenderer = PdfRenderer(parcelFileDescriptor)
                val pageCount = pdfRenderer.pageCount
                for (i in 0 until pageCount) {
                    val page = pdfRenderer.openPage(i)
                    val width = resources.displayMetrics.densityDpi / 72 * page.width
                    val height = resources.displayMetrics.densityDpi / 72 * page.height
                    val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
                    val canvas = Canvas(bitmap)
                    canvas.drawColor(Color.WHITE)
                    canvas.drawBitmap(bitmap, 0f, 0f, null)
                    page.render(
                        bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY
                    )
                    imgList.add(
                        ImageUtils.saveBitmapJPG(
                            mContext, bitmap, App.getContext().cacheTempPath
                        )
                    )
                    mPdfPageSize.add(Pair(page.width, page.height))
                    page.close()
                }
                parcelFileDescriptor.close()
                pdfRenderer.close()
            }
            it.onNext(imgList)
            it.onComplete()
        }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe({imgList->
                dismissTip()
                Log.e("subscribe",""+imgList)
                imgList.forEach {
                    fragments.add(SignPreviewItemFragment.load(it))
                }
                qvp_sign_preview.adapter = FragmentAdapter(supportFragmentManager, fragments)
            }, {
                dismissTip()
                showErrorTip("删除异常")
            })


    }

    override fun onInitData() {
        topBar.setTitle("预览文件")

        topBar.addLeftBackImageButton().singleClick { doOnBackPressed() }
        val fileId = mFileModel?.fileId
        if (mFileModel.type == Params.fileTypeWord) {
            imageVoList.forEach {
                fragments.add(SignPreviewItemFragment.load(it.url))
            }
            qvp_sign_preview.adapter = FragmentAdapter(supportFragmentManager, fragments)
        } else if (mFileModel.type == Params.fileTypePdf) {
            pdfSign()
        } else {
            if (fileId != null) {
                if (fileId.contains(",")) {
                    val splits = fileId.split(",")
                    splits.forEach {
                        fragments.add(
                            SignPreviewItemFragment.load(
                                OssRequest.getInstance().getFileUrl(it)
                            )
                        )
                    }
                } else {
                    fragments.add(
                        SignPreviewItemFragment.load(
                            OssRequest.getInstance().getFileUrl(fileId)
                        )
                    )
                }
                qvp_sign_preview.adapter = FragmentAdapter(supportFragmentManager, fragments)
            }
        }



    }

    override fun onSave() {

    }

    override fun getContentViewId() = R.layout.activity_sign_preview
}